package com.uraurora.crescent.util;

import com.google.common.collect.Lists;

import java.lang.reflect.Array;
import java.util.*;

public final class SeiIterables {

    private SeiIterables(){}

    public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
        Collection<? extends T> collection = toCollection(iterable);
        T[] array = newArray(type, collection.size());
        return collection.toArray(array);
    }

    public static Object[] toArray(Iterable<?> iterable, int size) {
        Object[] obj = new Object[size];
        int index = 0;
        Iterator<?> it = Objects.requireNonNull(iterable).iterator();
        while(index < size && it.hasNext()){
            obj[index++] = it.next();
        }
        return obj;
    }

    @SuppressWarnings("unchecked")
    private static <T> T[] newArray(Class<T> type, int length) {
        return (T[]) Array.newInstance(type, length);
    }

    public static <T> Collection<T> toCollection(Iterable<T> iterable) {

        if(iterable instanceof Collection){
            return (Collection<T>) iterable;
        }
        else{
            List<T> res = Lists.newArrayList();
            for(T o : iterable){
                res.add(o);
            }
            return res;
        }
    }


}
